package com.xiaoq.sites.endpoint;

import java.util.ArrayList;
import java.util.List;

import com.xiaoq.coms.GenericDataResponse;
import com.xiaoq.qiniu.QiNiuSpaceEnum;
import com.xiaoq.qiniu.UploadUtil;
import com.xiaoq.vo.PagingVo;
import io.swagger.annotations.*;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import com.xiaoq.coms.GenericListResponse;
import com.xiaoq.coms.GenericResponse;
import com.xiaoq.sites.entity.BannerEntity;
import com.xiaoq.sites.service.IBannerService;
import com.xiaoq.sites.vo.BannerVo;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;

@RestController
@RequestMapping("/api/v1/banner")
public class BannerEndpoint {
	
	@Autowired
	private IBannerService bannerSer;
	
	private class BannerListResponse extends GenericListResponse<BannerVo>{}

	private static final class BannerResponse extends GenericDataResponse<BannerVo> {};

	private static final Logger LOG = LoggerFactory.getLogger(BannerEndpoint.class);
	
	@ApiOperation(value="Banner列表", notes="Banner列表")
	@ApiResponses({
		@ApiResponse(code = 200, response = BannerListResponse.class, message = "Banner列表")
	})
	@GetMapping(value="/{userId}", produces={MediaType.APPLICATION_JSON_UTF8_VALUE})
	public ResponseEntity<?> bannerListView(
			@PathVariable(value="userId",required=false)@ApiParam(value="userId个性化推荐备用",required=false)String userId,
			@RequestParam(value="channelCode",required=true)@ApiParam(value="1000首页Banner2000为发现页Banner",required=true)String channelCode,
			@RequestParam(value="cityCode",required=false)@ApiParam(value="所在市编码（channelCode为20时传）",required=false)String cityCode){
		if(StringUtils.isNotEmpty(channelCode)){
			List<BannerEntity> bannerEntityList = bannerSer.findBannerList(channelCode,cityCode);
			List<BannerVo> bannerVoList = new ArrayList<>();
			BannerVo bannerVo = null;
			for(BannerEntity banner: bannerEntityList){
				bannerVo = new BannerVo();
				BeanUtils.copyProperties(banner, bannerVo);
				bannerVoList.add(bannerVo);
			}
			return BannerListResponse.listNoCount(bannerVoList);
		}else{
			return GenericResponse.ng("请传递具体版面Id");
		}

	}

	/**
	 *  首页 banner的 insert
	 * */
	@ApiOperation(value="Banner信息的插入操作[政府端添加功能]", notes="Banner信息的插入操作[政府端添加功能]")
	@ApiResponses({
			@ApiResponse(code = 200, response = GenericResponse.class, message = "Banner信息的插入操作[政府端添加功能]成功or失败")
	})
	@PostMapping(value="/add", produces={MediaType.APPLICATION_JSON_UTF8_VALUE})
	public ResponseEntity<?> bannerListView(
		@RequestParam(value = "sortNum",required = false) @ApiParam(value = "序号(排序)") Integer sortNum,
		@RequestParam(value = "linkParams",required = false) @ApiParam(value = "跳转参数") String linkParams,
		@RequestParam(value = "channelCode",required = false) @ApiParam(value = "板块编码（首页：1000，发现页：2000）") String channelCode,
		@RequestParam(value = "channelName",required = false) @ApiParam(value = "板块名称（首页：view，发现页：find）") String channelName,
		@RequestParam(value = "title",required = false) @ApiParam(value = "标题") String title,
		@RequestParam(value = "descriptions",required = false) @ApiParam(value = "文字描述") String descriptions,
		@RequestParam(value = "mainImg",required = false) @ApiParam(value = "主图URL") MultipartFile mainImg,
		@RequestParam(value = "zoneProvince",required = false) @ApiParam(value = "区划省") String zoneProvince,
		@RequestParam(value = "zoneCity",required = false) @ApiParam(value = "区划市") String zoneCity,
		@RequestParam(value = "zoneDistrict",required = false) @ApiParam(value = "区划区") String zoneDistrict,
		@RequestParam(value = "memo",required = false) @ApiParam(value = "备注") String memo){


		BannerEntity bannerEntity =new BannerEntity();

		if(null !=sortNum){
			bannerEntity.setSortNum(sortNum);
		}

		if(!org.springframework.util.StringUtils.isEmpty(linkParams)){
			bannerEntity.setLinkParams(linkParams);
		}

		if(!org.springframework.util.StringUtils.isEmpty(channelCode)){
			bannerEntity.setChannelCode(channelCode);
		}

		if(!org.springframework.util.StringUtils.isEmpty(channelName)){
			bannerEntity.setChannelName(channelName);
		}

		if(!org.springframework.util.StringUtils.isEmpty(title)){
			bannerEntity.setTitle(title);
		}

		if(!org.springframework.util.StringUtils.isEmpty(descriptions)){
			bannerEntity.setDescriptions(descriptions);
		}

		if(null != mainImg){
			String imgUrl = "";
			try {
				if (mainImg != null && mainImg.getSize()>0) {
					imgUrl = UploadUtil.easyUploadByte(mainImg, QiNiuSpaceEnum.XIAOQ_SITES.getName().toLowerCase(),
							QiNiuSpaceEnum.XIAOQ_SITES.getDomain());
				}else {
					return GenericResponse.ng("上传的图片为空");
				}
			} catch (Exception e) {
				LOG.error("七牛云上传异常！", e);
				return GenericResponse.ng("图片上传失败！");
			}

			bannerEntity.setMainImgUrl(imgUrl);

		}

		if(!org.springframework.util.StringUtils.isEmpty(zoneProvince)){
			bannerEntity.setZoneProvince(zoneProvince);
		}
		if(!org.springframework.util.StringUtils.isEmpty(zoneCity)){
			bannerEntity.setZoneCity(zoneCity);
		}
		if(!org.springframework.util.StringUtils.isEmpty(zoneDistrict)){
			bannerEntity.setZoneDistrict(zoneDistrict);
		}
		if(!org.springframework.util.StringUtils.isEmpty(memo)){
			bannerEntity.setMemo(memo);
		}

		bannerSer.addBanner(bannerEntity);
		return GenericResponse.ok();
	}


	/**
	 *  首页 banner的 delete
	 * */
	@ApiOperation(value="Banner信息的删除操作", notes="Banner信息的删除操作，传入主键id")
	@ApiResponses({
			@ApiResponse(code = 200, response = GenericResponse.class, message = "Banner信息的删除操作，返回成功or失败")
	})
	@DeleteMapping(value="/delete/{bannerId}")
	public ResponseEntity<?> delete(@PathVariable("bannerId") @ApiParam(value="bannerId", required=true) String bannerId,HttpServletRequest reques){

		if(org.springframework.util.StringUtils.isEmpty(bannerId)){
			return GenericResponse.ng("请求参数为空");
		}

		boolean result = bannerSer.delBanner(bannerId);
		if( result){
			return GenericResponse.ok();
		}
		return GenericResponse.ng("删除失败");
	}


	@ApiOperation(value="修改Banner信息" ,notes="修改Banner信息")
	@ApiResponses({
			@ApiResponse(code=200, response=GenericResponse.class, message="修改Banner信息")
	})
	@PutMapping(value="/update", produces={MediaType.APPLICATION_JSON_UTF8_VALUE})
	public ResponseEntity<?> updateRoute(@ApiParam(value="bannerVo", required=true)  @RequestBody BannerVo bannerVo, HttpServletRequest request) {

		BannerEntity bannerEntity =new BannerEntity();
		BeanUtils.copyProperties(bannerVo,bannerEntity);
		boolean result = bannerSer.updateBanner(bannerEntity);
		if(result){
			return GenericResponse.ok();
		}

		return GenericResponse.ng("修改失败");

	}


	@ApiOperation(value="根据id获取Banner", notes="根据id查询Banner")
	@ApiResponses({
			@ApiResponse(code = 200, response = BannerResponse.class, message = "根据id查询Banner")
	})
	@GetMapping(value="/getBannerById/{bannerId}")
	public ResponseEntity<?> routeList(@PathVariable("bannerId") @ApiParam(value="bannerId", required=true) String bannerId,HttpServletRequest request) {


		if(org.springframework.util.StringUtils.isEmpty(bannerId)){
			return GenericResponse.ng("bannerId不能为空");
		}
		try{
			BannerEntity bannerEntity = bannerSer.findByBannerId(bannerId);
			return BannerResponse.okWithData(bannerEntity);
		}catch (Exception e){
			return GenericResponse.ng("内部错误，查询失败请联系管理员！");
		}
	}



	@ApiOperation(value = "banner列表", notes = "banner列表查询")
	@ApiResponses({ @ApiResponse(code = 200, response = BannerListResponse.class, message = "banner列表查询") })
	@GetMapping(value = "/getBannerList", produces = { MediaType.APPLICATION_JSON_UTF8_VALUE })
	public ResponseEntity<?> getBannerList(@ModelAttribute(value = "pvo") PagingVo pvo,
	   	@RequestParam(value="channelCode",required=false)@ApiParam(value="1000首页Banner2000为发现页Banner",required=false)String channelCode,
	   	@RequestParam(value="cityCode",required=true)@ApiParam(value="所在市编码",required=true)String cityCode, HttpServletRequest request) {

			List<BannerEntity> bannerEntityList = bannerSer.findBannerByChannelCodeAndCityCodeList(pvo,channelCode,cityCode);
			List<BannerVo> bannerVoList = new ArrayList<>();
			BannerVo bannerVo = null;
			if(CollectionUtils.isNotEmpty(bannerEntityList)) {
				for (BannerEntity banner : bannerEntityList) {
					bannerVo = new BannerVo();
					BeanUtils.copyProperties(banner, bannerVo);
					bannerVoList.add(bannerVo);
				}
			}
			return BannerListResponse.listAndCount(bannerVoList,bannerVoList.size());
	}

}
